#include "panel.h"

#include <stdlib.h>

#include "global.h"
#include "drawing.h"
#include "text.h"
#include "toolbar.h"

static const int WIDTH = 200;
static const int MARGIN = 14;

Panel* new_panel()
{
	Panel* panel = malloc(sizeof(Panel));
	panel->dirty = true;
	panel->w = WIDTH;
	panel->state = OPEN;
	return panel;
}


void redraw_panel(Panel* panel)
{
	if(panel->dirty)
	{
		// panel background
		fill_3d_box(screen, &(SDL_Rect) {
				screen->w - panel->w, -2,
				panel->w + 2, screen->h + 4 }, UPPER);
		SDL_BlitSurface(images[PANEL_OPENER], NULL, screen, &(SDL_Rect) {
				screen->w - panel->w + 3, 3});

		// city information
		Pencil p = { screen, editundo14, (SDL_Color){255,255,255},
			(SDL_Color){0,0,0} };
		SDL_Surface* name = dbl_text(p, 0, city->name);
		SDL_BlitSurface(name, NULL, screen, 
				&(SDL_Rect) { screen->w - panel->w + 30, 6 });
		SDL_FreeSurface(name);

		// update screen
		SDL_UpdateRect(screen, screen->w - panel->w, 0, panel->w,
				screen->h);
		panel->dirty = false;
	}
}


void panel_mouse_button(Panel* panel, SDL_MouseButtonEvent b)
{
	if(b.x < 24 && b.y < 24 && (panel->state == OPEN || panel->state == OPENING))
		panel->state = CLOSING;
	else if((b.x < 24) && (panel->state == CLOSED || panel->state == CLOSING))
		panel->state = OPENING;
}


void panel_process(Panel* panel)
{
	if(panel->state == OPENING)
	{
		panel->dirty = true;
		panel->w += 4;
		if(panel->w >= WIDTH)
		{
			panel->state = OPEN;
			panel->w = WIDTH;
		}
	}
	else if(panel->state == CLOSING)
	{
		panel->dirty = true;
		panel->w -= 4;
		if(panel->w <= MARGIN)
		{
			panel->state = CLOSED;
			panel->w = MARGIN;
		}
	}
}


void free_panel(Panel* panel)
{
	free(panel);
}
